<template>
  <view class="wrapper" :style="specialStyle" @touchstart="$emit('closeBubble')">
    <view class="majorFilterContainer">
      <!-- <scroll-view :scroll-x="true" class="firstListContainer" scroll-with-animation
        :scroll-into-view='scollFirstToView'>
        <view v-for="item,index in majorFirstList" :key="index"
          :class="{'firstListItem':true, 'selectedFirst':item.positionTagId==selectedFirstId}" :id="`first-${index}`"
          @click="handleFirstItemClick(item,index)">
          {{item.tagName}}
        </view>
      </scroll-view> -->
      <view class="firstListContainer">
        <u-tabs :list="majorFirstList" bg-color="transparent" :height="100" inactive-color="#222" active-color="#222"
          :bar-style="{ display: 'none' }" name="tagName" :is-scroll="true" :current="selectedFirstIndex"
          @change="handleFirstItemClick" :gutter="28" :active-item-style="tabActiveStyle">
        </u-tabs>
      </view>

      <view class="mainListContainer">
        <scroll-view :scroll-y="true" :scroll-top="scrollSecondTop" scroll-with-animation class="secondPositionList">
          <view :class="{
              SecondPositionItem: true,
              'u-line-2': true,
              selectedSecond: item.positionTagId == selectedSecondId,
            }" v-for="(item, index) in secondPositionList" :key="index" @click="handleSecondItemClick(item, index)">
            <span v-if="item.tagName == '热门'" class="hotSecondPosition">
              <img src="https://img3.job1001.com/ypMp/elan/images/career/hotSecondPosition.png" />
              {{ item.tagName }}</span>
            <span v-else>{{ item.tagName }}</span>
          </view>
        </scroll-view>
        <scroll-view :scroll-y="true" scroll-with-animation class="thirdPositionList"
          :scroll-into-view="scollThirdToView" @scroll.native="handleScroll" ref="scollView">
          <view class="ThirdPositionItem" v-for="(item, index) in secondPositionList" :key="index"
            :id="`third-${index}`">
            <view :class="{ thirdTitle: true, fixedTitle: item.isFixTitle }">
              <template v-if="item.tagName == '热门'">
                {{ item.tagName }}
                <text class="titleTip">大家都在搜的{{ selectedFirstName }}专业</text>
              </template>
              <template v-else>
                {{ item.tagName }}
                <text class="titleTip">({{ item.children.length || "0" }}个)</text>
              </template>
            </view>
            <view class="thirdChildrenList">
              <view class="thirdChildrenItem" v-for="(_item, _index) in item.children" :key="_index"
                @click="handleThirdItemClick(_item)">
                <view class="thirdChildrenItemTitle">
                  {{ _item.tagName }} - {{ _item.tagCode }}
                </view>
                <view class="thirdChildrenItemTags">
                  <view class="tagItem" v-if="_item.tagTimeDesc">{{
                    _item.tagTimeDesc
                  }}</view>
                  <view class="tagItem" v-if="_item.tagDesc">{{
                    _item.tagDesc
                  }}</view>
                </view>
              </view>
            </view>
          </view>
        </scroll-view>
      </view>
    </view>
  </view>
</template>

<script>
import { getPositionTagList, getPositionTagTree } from "@/api/modules/major";
import { addBuryingPoint } from "@/api/modules/career";
export default {
  name: "majorFilterList",
  props: {
    cateType: {
      type: String,
      default: "30",
    },
    specialStyle: {
      type: Object,
      default: () => {},
    },
  },
  data() {
    return {
      majorFirstList: [],
      secondPositionList: [],
      ThirdPositionList: [],
      selectedFirstId: "", //第一层选中的id
      selectedFirstName: "", //第一层选中的名字
      selectedFirstIndex: "", //第一层选中的下标
      scollFirstToView: "", //控制第一层筛选容器滚动的变量
      selectedSecondId: "", //第二层选中的id
      selectedSecondIndex: 0, //第二层选中的下标
      scrollSecondTop: 0, //第二层的滚动高度
      scollThirdToView: "", //控制第三层筛选容器滚动的变量
      distance: 0,
      isClickTab: false, //是否是点击滚动
      secondHeightArr: [], //第二层每一个专业的高度
      heightArr: [], //第三层每一个二级专业的高度
      tabActiveStyle: {
        "justify-content": "center",
        "align-items": "center",
        border: "4rpx solid #f75a3e",
        background: "linear-gradient(180deg, #ffece9 0%, #ffffff 100%)",
        "border-radius": "12rpx",
        "line-height": "98rpx",
      },
      buryingPointId: "",
      cardType: "",
    };
  },
  methods: {
    //普通的埋点+事件停留埋点
    async addBuryingPointFn(
      etId,
      statType,
      jumpPersonId,
      jumpSource,
      sourceType
    ) {
      const params = {
        etId: etId,
        id: this.buryingPointId ? this.buryingPointId : "", //后台要求不能传空，未登录也要统计
        personId: uni.getStorageSync("person-id").slice(2) || "0",
        cardType: this.cardType
          ? this.cardType
          : uni.getStorageSync("cardType") || this.cardType,
        consultantId: uni.getStorageSync("sellId")
          ? uni.getStorageSync("sellId")
          : "",
        originType: this.originFrom == "shareLink" ? 10 : 20,
        statType: statType ? statType : "10",
        jumpPersonId: jumpPersonId,
        jumpSource: jumpSource,
        sourceType: sourceType,
      };
      const res = await addBuryingPoint(params);
    },
    //专科本科改变将index设为0
    currentIndexZero() {
      this.selectedFirstIndex = 0;
    },
    //获取第一层
    reqGetPositionTagList() {
      getPositionTagList({
        tagLevel: "1",
        tagType: "10",
        cateType: this.cateType,
      })
        .then((res) => {
          if (res.code == 200) {
            this.majorFirstList = res.data || [];
            if (res.data.length) {
              this.selectedFirstId = res.data[0].positionTagId;
              this.selectedFirstName = res.data[0].tagName;
              this.reqGetPositionTagTree(res.data[0].positionTagId);
              this.scollFirstToView = ""; //需要先重置一下
              setTimeout(() => {
                this.scollFirstToView = "first-0"; //重置一下第三层滚动
              });
            }
          }
        })
        .catch((err) => {});
    },
    //获取第二层
    reqGetPositionTagTree(positionTagId) {
      //根据一级专业Id获取二级和三级列表，每次tab点击都会调用
      getPositionTagTree({
        positionTagId: positionTagId,
        tagType: "10",
        cateType: this.cateType,
        searchRecommendType: 10,
      })
        .then((res) => {
          if (res.code == 200) {
            this.secondPositionList = res.data || [];
            this.selectedSecondId = res.data[0].positionTagId;
            this.cacSecondHeight();
            this.cacHeight();
            this.selectedSecondIndex = 0;
            this.isClickTab = true;
            setTimeout(() => {
              this.isClickTab = false;
            }, 300);
            this.scollThirdToView = ""; //需要先重置一下
            setTimeout(() => {
              this.scollThirdToView = "third-0"; //重置一下第三层滚动
              this.$set(
                this.secondPositionList[this.selectedSecondIndex],
                "isFixTitle",
                true
              );
            });
          }
        })
        .catch((err) => {});
    },
    handleFirstItemClick(index) {
      this.addBuryingPointFn(20074, "", "", "", "");
      this.selectedFirstId = "";
      const item = this.majorFirstList[index];
      this.selectedFirstId = item.positionTagId;
      this.selectedFirstName = item.tagName;
      this.selectedFirstIndex = index;
      this.scollFirstToView = "first-" + index;
      this.reqGetPositionTagTree(item.positionTagId);
    },
    handleSecondItemClick(item, index) {
      this.addBuryingPointFn(20075, "", "", "", "");
      if (this.isClickTab) return;
      this.isClickTab = true;
      setTimeout(() => {
        this.isClickTab = false;
      }, 500);
      this.selectedSecondId = item.positionTagId;
      this.selectedSecondIndex = index;
      this.scollThirdToView = "";
      this.$nextTick(() => {
        this.scollThirdToView = "third-" + index;
      });
    },
    handleThirdItemClick(_item) {
      this.addBuryingPointFn(20076, "", "", "", "");
      // 这里点击跳转到职业职业详情
      let pageName = "专业搜索列表页";
      let params = {
        positionOrMajor: 1,
        levelNum: 3,
        tagName: _item.tagName,
        positionTagId: _item.positionTagId,
        advertise: true,
        pageName,
      };
      getApp().globalData.allCategoryParams = params;
      // uni.switchTab({
      //   url: "/pages/career/positionDictionary/allCategory",
      // });
      uni.navigateTo({
        url:
          `/pagesSub/careerNew/majorDetail/index?positionTagId=` +
          _item.positionTagId,
      });
      console.log("这里发生即将发生跳转", _item.positionTagId);
    },
    handleScroll(e) {
      if (this.isClickTab) return;
      this.$emit("closeBubble");
      let scrollTop = e.detail.scrollTop; //获取距离顶部的距离;
      //现在的item的高度
      const nowHeight = this.heightArr[this.selectedSecondIndex];
      //上一个的高度
      const preHiehgt = this.heightArr[this.selectedSecondIndex - 1];
      //处理第三层的滚动
      if (scrollTop > nowHeight) {
        this.selectedSecondId =
          this.secondPositionList[this.selectedSecondIndex + 1].positionTagId;
        this.selectedSecondIndex += 1;
        //如果滚动到顶部以后了，那就得固定一下title
        this.$set(
          this.secondPositionList[this.selectedSecondIndex],
          "isFixTitle",
          true
        );
      } else if (scrollTop < preHiehgt) {
        if (this.secondPositionList[this.selectedSecondIndex - 1]) {
          this.selectedSecondId =
            this.secondPositionList[this.selectedSecondIndex - 1].positionTagId;
          this.selectedSecondIndex -= 1;
          this.$set(
            this.secondPositionList[this.selectedSecondIndex],
            "isFixTitle",
            true
          );
        }
      }
      //处理二级跟随滚动
      this.scrollSecondTop =
        this.secondHeightArr[this.selectedSecondIndex] -
        parseInt(this.specialStyle.height.slice(0, -2) / 2);
    },
    cacHeight() {
      this.$nextTick(() => {
        let list = [];
        let height = 0;
        const query = uni.createSelectorQuery().in(this);
        query.selectAll(".ThirdPositionItem").boundingClientRect();
        query.exec((res) => {
          res[0].forEach((item) => {
            height += parseInt(item.height);
            list.push(height);
          });
          this.heightArr = list;
        });
      });
    },
    //计算二级的每个高度
    cacSecondHeight() {
      this.$nextTick(() => {
        let list = [];
        let height = 0;
        const query = uni.createSelectorQuery().in(this);
        query.selectAll(".SecondPositionItem").boundingClientRect();
        query.exec((res) => {
          res[0].forEach((item) => {
            height += parseInt(item.height);
            list.push(height);
          });
          this.secondHeightArr = list;
          console.log("secondHeightArr", this.secondHeightArr);
        });
      });
    },
  },
  created() {
    this.reqGetPositionTagList();
  },
  watch: {
    cateType(newValue, oldValue) {
      if (newValue) {
        this.reqGetPositionTagList();
      }
    },
  },
};
</script>

<style lang="scss" scoped>
.wrapper {
  margin-top: 26rpx;
  width: 100vw;
  min-height: 400rpx;
  overflow: hidden;

  .majorFilterContainer {
    .firstListContainer {
      // display: flex;
      height: 100rpx;
      // padding: 0 32rpx;
      width: 100vw;
      margin-bottom: 38rpx;

      // white-space: nowrap; /* 禁止换行，很重要 */
      // overflow-x: hidden; /* 显示滚动条 */
      // scroll-snap-type: x mandatory; /* 开启滚动吸附 */
      .firstListItem {
        display: inline-flex;
        justify-content: center;
        align-items: center;
        scroll-snap-align: center;
        /* 设置吸附位置 */
        height: 100rpx;
        padding: 0 28rpx;
        margin-right: 16rpx;
        border-radius: 12rpx;
        border: 2rpx solid #e4e5f5;
        background: linear-gradient(180deg, #ebf5fe 0%, #ffffff 100%);

        &.selectedFirst {
          border: 4rpx solid #f75a3e;
          background: linear-gradient(180deg, #ffece9 0%, #ffffff 100%);
        }

        &:last-of-type {
          margin-right: 0rpx;
        }
      }
    }
  }

  .mainListContainer {
    display: flex;

    // justify-content: start;
    .secondPositionList {
      // display: flex;
      // flex-direction: column;

      height: 1188rpx;
      background-color: #f4f6f8;

      .SecondPositionItem {
        display: flex;
        // justify-content: center;
        align-items: center;
        // width: 212rpx;
        padding-left: 32rpx;
        height: 100rpx;
        background: #f4f6f8;
        color: #666666;

        span {
          // display: inline-flex;
          // justify-content: center;
          // align-items: center;
          text-align: left;
          max-width: 160rpx;
          font-size: 28rpx;
          // overflow: hidden;
          // white-space: nowrap;
          // text-overflow: ellipsis;
        }

        .hotSecondPosition {
          display: inline-flex;
          justify-content: flex-start;
          align-items: center;

          img {
            width: 28rpx;
            height: 36rpx;
            margin-right: 14rpx;
          }
        }
      }

      .selectedSecond {
        position: relative;
        background: #ffffff;
        font-weight: bold;
        color: #222222;

        &::after {
          content: "";
          position: absolute;
          bottom: -30rpx;
          right: 0rpx;
          height: 30rpx;
          width: 30rpx;
          background-image: url($img-base + "career/positionDictionary/radiuBorder.png");
          background-repeat: no-repeat;
          background-size: 100% 100%;
        }

        &::before {
          content: "";
          position: absolute;
          top: -30rpx;
          right: 0rpx;
          height: 30rpx;
          width: 30rpx;
          background-image: url($img-base + "career/positionDictionary/topRadiuBorder.png");
          background-repeat: no-repeat;
          background-size: 100% 100%;
        }
      }
    }

    .thirdPositionList {
      position: relative;
      height: 1188rpx;
      background-color: white;
      margin-left: -2rpx;

      .ThirdPositionItem {
        display: flex;
        flex-direction: column;
        border-bottom: 10rpx solid #f4f6f7;

        &:last-of-type {
          overflow: hidden;
          border-bottom: none;
          padding-bottom: 100rpx;
        }

        .thirdTitle {
          display: flex;
          align-items: center;
          width: 538rpx;
          height: 100rpx;
          padding: 0rpx 32rpx;
          overflow: hidden;
          white-space: nowrap;
          text-overflow: ellipsis;

          .titleTip {
            font-size: 26rpx;
            font-family: PingFangSC-Regular, PingFang SC;
            font-weight: 400;
            color: #888888;
            line-height: 30rpx;
            padding-left: 16rpx;
          }
        }

        .fixedTitle {
          position: sticky;
          top: 0;
          z-index: 2;
          background-color: white;
        }

        .thirdChildrenList {
          display: flex;
          flex-direction: column;

          .thirdChildrenItem {
            display: flex;
            flex-direction: column;
            // width: 538rpx;
            min-height: 124rpx;

            padding: 24rpx 0;
            margin: 0 32rpx;
            border-bottom: 1.2rpx solid #f5f5f5;

            .thirdChildrenItemTitle {
              font-size: 28rpx;
              font-family: PingFangSC;
              font-weight: bold;
              color: #222222;
              line-height: 30rpx;
              margin-bottom: 16rpx;
            }

            .thirdChildrenItemTags {
              display: flex;

              .tagItem {
                display: flex;
                align-items: center;
                height: 30rpx;
                // line-height: 28rpx;
                font-size: 20rpx;
                padding: 0 6rpx;
                background: rgba(255, 119, 49, 0.05);
                border-radius: 6rpx;
                border: 1rpx solid #ff836c;
                color: #fa7259;
                margin-right: 16rpx;
              }
            }
          }
        }
      }
    }
  }
}

.u-tab-item {
  border: none;
  background: #f5f5f5;
}
</style>
